/*
 * @Description:express中使用session认证
 * @Author: 小雨
 * @Date: 2024-07-01 17:16:37
 * @LastEditTime: 2024-07-02 11:06:18
 * @LastEditors: 小雨
 */
const express = require('express');
const session = require('express-session');

const app = express();

//配置中间件
app.use(
    session({
        secret: 'guagua',
        resave: false,
        saveUninitialized: true,
    })
);

app.use(express.urlencoded({ extened: false }));

app.post('/api/login', (req, res) => {
    if (req.body.username !== 'admin' && req.body.password !== 111) {
        return res.send({ status: 1, msg: '登录失败' });
    }
    //将登陆成功用户存到session中 必须要配置express-session这个中间件
    req.session.user = req.body;
    req.session.isLogin = true;

    res.send({ status: 0, msg: '登录成功' });
});

app.get('/api/username', (req, res) => {
    if (!req.session.isLogin) {
        return res.send({ status: 1, msg: '登录失败' });
    }
    res.send({ status: 0, msg: 'success', username: req.session.user.username });
});

app.post('/api/logout', (req, res) => {
    //清空当前客户端对应的session信息
    req.session.destroy();
    res.send({ status: 0, msg: '退出登录成功' });
});

app.listen(80, () => {
    console.log('服务器启动');
});
